//
//  iCloudTools.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import Foundation
import UIKit

final public class iCloudTools {
    
    // 判断iCould是否可用
    public static func enable() -> Bool {
        let url = FileManager.default.url(forUbiquityContainerIdentifier: nil)
        return (url != nil)
    }
    
    // 下载文件
    public static func downloadFile(WithDocumentUrl url: URL, completion: ((Data) -> Void)? = nil) {
        let document = YBDocument(fileURL: url)
        document.open { (success) in
            if success {
                document.close(completionHandler: nil)
            }
            if let callback = completion, let data = document.data {
                callback(data as Data)
            }
        }
    }
}

// 文件管理
class YBDocument: UIDocument {
    
    var data: Data?
    var imgData: Data?
    
   // 处理文件上传
    override func contents(forType typeName: String) throws -> Any {
        if typeName == "public.png" {
            return imgData ?? Data()
        } else {
            return Data()
        }
    }
    
    // 处理文件下载
    override func load(fromContents contents: Any, ofType typeName: String?) throws {
        if let userContent = contents as? Data {
            data = userContent
        }
    }
}
